import { useModel } from '@@/exports';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import {
  batchDeleteFun,
  getUserFileNumberFun,
  panAddDirFun,
} from '@/services/ant-design-pro/panApi';
import { Avatar, Button, Flex, Input, message, Modal, Progress, Upload, UploadProps } from 'antd';
import { formatBits } from '@/utils';
import {
  UploadOutlined,
  FolderAddOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
} from '@ant-design/icons';
import AliSvg from '@/components/AliSvg';
import FilePopconfirm from '@/pages/filePan/FilePopconfirm';

interface AvatarNameProps {
  getCurrBread: () => any;
  updateTable: () => any;
  updateFileNumber: () => any;
}

const AvatarName = forwardRef((props: AvatarNameProps, ref) => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  let [fileNumber, setFileNumber] = useState({ currentNumber: 0, allNumber: 0, percent: 0 });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [dirName, setDirName] = useState('');
  const popconfirmRef = useRef();
  const { confirm } = Modal;
  const { selectList, setSelectList } = useModel('itemSelect');

  const changeDir = (val) => {
    setDirName(val.currentTarget.value);
  };

  // 获取用户使用容量
  function getUserFileSize() {
    getUserFileNumberFun().then((res) => {
      setFileNumber({
        ...res.data,
        percent: (res.data.currentNumber / res.data.allNumber) * 100,
      });
    });
  }

  useEffect(() => {
    getUserFileSize();
  }, []);

  // 文件上传
  const uploadProps: UploadProps = {
    showUploadList: false,
    // 允许多选
    multiple: true,
    // 自定义文件上传
    async customRequest(options) {
      console.log(options.file, '66666');
      // 获取文件，把文件交给上传列表组件进行上传
      let filePid = props.getCurrBread().filePid;
      popconfirmRef.current.addFileList(options.file, filePid);
    },
  };

  // 更新方法
  const updateTable = () => {
    getUserFileSize();
    props.updateTable();
  };

  // 已使用容量组件
  const formatProgress = () => {
    return `${formatBits(fileNumber.currentNumber)} / ${formatBits(fileNumber.allNumber)}`;
  };

  // 新建文件夹
  const addDir = () => {
    setDirName('');
    setIsModalOpen(true);
  };

  const submitAddDir = () => {
    if (!dirName) {
      message.error('文件夹名称不能为空');
      return;
    }
    panAddDirFun({
      fileName: dirName,
      filePid: props.getCurrBread().filePid,
      fileSize: 0,
    }).then(() => {
      message.success('新建文件夹成功');
      getUserFileSize();
      props.updateTable();
      setIsModalOpen(false);
    });
  };

  const closeDirModal = () => {
    setIsModalOpen(false);
  };

  useImperativeHandle(ref, () => {
    return {
      getUserFileSize,
    };
  });

  const batchDelete = () => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleFilled />,
      content: '确认删除所选文件吗?',
      onOk: async () => {
        let fileIds = selectList.map((item) => item.fileId).join(',');
        await batchDeleteFun(fileIds);
        message.success('删除成功');
        setSelectList([]);
        props.updateTable();
        props.updateFileNumber();
      },
    });
  };

  return (
    <>
      <Flex gap={10} align={'center'} justify={'space-between'}>
        <Flex gap={10}>
          <Avatar size={45} src={currentUser.avatar} />
          <div style={{ width: '200px' }}>
            <div>{currentUser.userName}</div>
            <Progress percent={fileNumber.percent} format={formatProgress} />
          </div>
        </Flex>

        <Flex gap={10} align={'center'}>
          {/*上传列表组件*/}
          <FilePopconfirm ref={popconfirmRef} updateTable={updateTable} />

          {selectList.length > 0 && (
            <Button danger icon={<DeleteOutlined />} onClick={batchDelete}>
              批量删除
            </Button>
          )}

          <Upload {...uploadProps}>
            <Button type={'primary'} icon={<UploadOutlined />}>
              上传文件
            </Button>
          </Upload>

          <Button type={'primary'} icon={<FolderAddOutlined />} onClick={addDir}>
            新建文件夹
          </Button>
        </Flex>
      </Flex>

      {/*新建文件夹弹框*/}
      <Modal
        title="新建文件夹"
        width={400}
        open={isModalOpen}
        onCancel={closeDirModal}
        onOk={submitAddDir}
      >
        <div className={'modal-body'}>
          <AliSvg href={'File'} size={'8em'} />
          <Input placeholder="请输入文件夹名称" value={dirName} onChange={changeDir} />
        </div>
      </Modal>
    </>
  );
});

export default AvatarName;
